package org.apdplat.realtimelog.manager;

import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class RedisManager {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    
    public Object get(String name) {
         ValueOperations<String,Object> ops = redisTemplate.opsForValue();
         return ops.get(name);
    }
    
    public void set(String key, Object value) {
        ValueOperations<String,Object> ops = redisTemplate.opsForValue();
        ops.set(key, value);
    }

    /**
     * 将数据存入Redis并设置失效时间
     * @param key   
     * @param latestHotelZone   value
     * @param timeout   失效时间
     * @param unit      时间类型
     */
    public void set(String key,Object value,Long timeout,TimeUnit unit){
        ValueOperations<String,Object> ops = redisTemplate.opsForValue();
        ops.set(key, value, timeout, unit);
    }
    
    /**
     * 删除
     * @param key
     */
    public void delete(String key){
        redisTemplate.delete(key);
    }
    
    /**
     * 模糊删除
     * @param pattern
     */
    public void deleteKeys(String pattern){
        Set<String> keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
    
    public boolean lock(String key, Long timeout, TimeUnit unit){
        Object obj = get(key);
        if (obj != null) {
            return false;
        }
        set(key, "lock", timeout, unit);
        return true;
    }
    
    public void unlock(String key){
        redisTemplate.delete(key);
    }
    
}

